package utils

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	log "github.com/sirupsen/logrus"
	"simulationFulu/models"
	"sort"
	"strconv"
	"strings"
)

func BuildFuluMd5Sign(callbackReq *models.CallbackReq, secret string) string {
	maps := map[string]string{
		"order_id":               strconv.FormatInt(callbackReq.OrderId, 10),
		"charge_finish_time":     callbackReq.ChargeFinishTime,
		"customer_order_no":      callbackReq.CustomerOrderNo,
		"order_status":           callbackReq.OrderStatus,
		"recharge_description":   callbackReq.RechargeDescription,
		"product_id":             strconv.Itoa(callbackReq.ProductId),
		"price":                  callbackReq.Price.Decimal.String(),
		"buy_num":                strconv.Itoa(callbackReq.BuyNum),
		"operator_serial_number": strconv.FormatInt(callbackReq.OperatorSerialNumber, 10),
	}
	log.Info(maps)
	// 序列化返回值
	b, er := json.Marshal(maps)
	if er == nil {
		log.Error(er)
	}
	s := SortChar(string(b))
	log.Info(s)
	sign := strings.ToLower(BuildMd5Str(s + secret))
	log.Info(sign)
	return sign
}

func SortChar(source string) string {
	length := len(source)
	array := make([]string, length)
	for i, v := range source {
		array[i] = string(v)
	}
	sort.Sort(sort.StringSlice(array))
	str := ""
	for _, v := range array {
		str += v
	}
	return str
}

func BuildMd5Str(source string) string {
	h := md5.New()
	h.Write([]byte(source))
	return hex.EncodeToString(h.Sum(nil))
}
